import requests, bs4
import os, time
import operator
from itertools import combinations, permutations
# import torch


class DoubleColorBall(object):
    def __init__(self):
        self.balls = {}
        self.baseUrl = 'http://tubiao.zhcw.com/tubiao/ssqNew/ssqJsp/ssqZongHeFengBuTuAsc.jsp'
        self.dataFile = './balls_data3.txt'

    def getHtml(self, url):
        headers = {
            'Referer': 'http://tubiao.zhcw.com/tubiao/ssqNew/ssqInc/ssqZongHeFengBuTuAsckj_year=2016.html',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
        }
        self.session = requests.Session()
        response = self.session.get(url, headers=headers)
        return response.text

    def getBall(self):
        for year in range(2003, 2023):
            url = self.baseUrl + '?kj_year=%s' % (year,)
            # print(url)
            html = self.getHtml(url)
            self.bs = bs4.BeautifulSoup(html, 'html.parser')
            if self.bs:
                data = self.bs.find_all(class_='hgt')
                self.parseBall(data)

    def parseBall(self, data):
        self.balls = {}
        for row in data:
            if not isinstance(row, bs4.element.Tag):
                continue
            center = row.find(class_="qh7").string.strip()
            # print(center)
            if center.startswith("模拟"):
                break
            redBalls = row.find_all(class_="redqiu")
            blueBall = row.find(class_="blueqiu3").string.strip()
            self.balls[center] = [r.string for r in redBalls] + [blueBall]

        self.saveBall(self.balls)

    def saveBall(self, data):
        with open(self.dataFile, 'a+') as f:
            for r in sorted(data, reverse=False):  # 降序
                # for r in sorted(data, reverse=True):  #升序
                f.write(str(r) + ' ' + ' '.join(data[r]) + '\n')
                lst.append(data[r])

lst = []
if __name__ == '__main__':
    ball = DoubleColorBall()
    ball.getBall()
    # 3 8 9 19 22 28   4
    # 1 7 10 12 22 25   1
    # 9 12 15 17 18 24   10
    # 11 14 23 26 30 33   15
    # 5 9 13 16 18 21    13
    temp_lst1 = ['3', '4', '5', '12', '15', '18', '3']
    temp_lst2 = ['1', '7', '9', '11', '14', '15', '4']
    temp_lst3 = ['3', '5', '17', '23', '26', '29', '5']
    temp_lst4 = ['1', '7', '10', '14', '19', '23', '1']
    temp_lst5 = ['2', '9', '19', '23', '27', '29', '6']
    if(temp_lst1 not in lst):
        print('temp1')
    if(temp_lst2 not in lst):
        print('temp2')
    if (temp_lst3 not in lst):
        print('temp3')
    if (temp_lst4 not in lst):
        print('temp4')
    if (temp_lst5 not in lst):
        print('temp5')